function [board] = findBoard(imorig,demo)
%findBoard Nalezeni hraci desky
%   Pomoci HSV transformace obrazu je nalezena hraci deska, ktera je
%   nasledne vyrotovana do roviny
%   board - nalezena hraci deska
%   imorig - originalni obraz

% transformace do HSV
im=rgb2hsv(imorig);

%separace na slozky
hue=im(:,:,1);
sat=im(:,:,2);
val=im(:,:,3);
g=imorig(:,:,2);

% filtrace spravnych hodnot
hue=hue<0.6 & hue>0.15;
sat=sat>0.15 & sat<0.6;
val=val>0.6;
g=g>170;

% fuze, uzavreni a zaplneni der
select=hue&sat&val&g;
select=imclose(select,ones(15));
select=imfill(select,'holes');
% Nejvetsi vhodny objekt
stats=regionprops(logical(select),'Area');
[~,ind]=max([stats.Area]); %index nejvetsiho objektu
board=bwlabel(select);
board=logical(board==ind);  %vyber nejvetsiho objektu
% xy=regionprops(board,'BoundingBox'); % nalezeni obdelnihoveho regionu s hraci deskou
% xy=[xy.BoundingBox]; %struct2array
% boardorig=imcrop(imorig,[floor(xy(1:2)),ceil(xy(3:4))]);  % orez
% board=imcrop(board,[floor(xy(1:2)),ceil(xy(3:4))]);
% Priprava pro rotace hledanim nejdelsi primky
bw=edge(board,'canny'); % nalezeni hran
[H, theta, rho] = hough(bw);
peaks= houghpeaks(H,1); % nejvyznamnejsi primka
line=houghlines(bw,theta,rho,peaks);
if demo
  figure
  imshow(bw)
  hold on
  for k = 1:length(line)
    xy = [line(k).point1; line(k).point2];
    plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');
    
    % Plot beginnings and ends of lines
    plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');
    plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');
  end
  title('Canny+Hough')
end

% hledani nejdelsi primky
% cara=zeros(CNT_LINE,2);
% for i=1:CNT_LINE
%   cara(i,:)=line(i).point1-line(i).point2;
% end
% [~,iline]=max(cara(1,:).^2+cara(2,:).^2);
iline=1;
%vypocet uhlu a rotace
cara=line(iline).point1-line(iline).point2;
uhel=atan(cara(2)/cara(1))*180/pi;
board=imrotate(board,uhel);
imorig=imrotate(imorig,uhel);
% nalezeni obdelnihoveho regionu s hraci deskou a vyriznuti
xy=regionprops(board,'BoundingBox');
xy=[xy.BoundingBox]; %struct2array
%board=imcrop(imorig,[floor(xy(1:2)),ceil(xy(3:4))]);
board=imcrop(imorig,[ceil(xy(1:2))+8,ceil(xy(3:4))-16]);
% pokud se nenasla z nejakeho duvodu hlavni primka, ale vedlejsi, tak se
% preklopi obraz do spravne polohy
if xy(4)>xy(3)
  newboard=uint8(zeros(size(board,2),size(board,1),3));
  newboard(:,:,1)=board(:,:,1)';
  newboard(:,:,2)=board(:,:,2)';
  newboard(:,:,3)=board(:,:,3)';
  board=newboard;
end
